package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.feignClient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author xiao
 * @Date 2024/12/23 上午 9:39
 * @ClassName: PasswordAuthService
 * @Description: 密码方式认证
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Resource
    XcUserMapper xcUserMapper;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    CheckCodeClient client;

    /**
     * @param authParamsDto
     * @return
     * @Desc: 账号密码认证
     */
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //校验验证码
/*        //todo 屏蔽验证码校验
        String checkcode = authParamsDto.getCheckcode();//获取用户输出的验证码
        String checkcodekey = authParamsDto.getCheckcodekey();//获取验证码的key

        if (checkcode ==null || checkcodekey ==null ){
            throw new RuntimeException("验证码为空或格式不正确");
        }

        //发起远程调用校验验证码
        Boolean b = client.verify(checkcodekey, checkcode);
        if  (!b){
             throw new RuntimeException("验证码校验失败");
        }*/

        //账号
        String username = authParamsDto.getUsername();
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if (xcUser == null) {
            throw new RuntimeException("账号不存在");
        }
        //将xcUser属性拷贝到XcUserExt
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        //校验密码
        String passwordForm = authParamsDto.getPassword();//传入的密码
        String passwordDb = xcUser.getPassword();//数据库获取的密码
        boolean b1 = passwordEncoder.matches(passwordForm, passwordDb);//比对密码
        if (!b1) {
            throw new RuntimeException("账号或密码错误");
        }
        //如果所有都通过 返回对象数据------>存入JWT中的username
        return xcUserExt;
    }
}
